package org.poc.camel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;

public class FTPFetch {
	
	private static void startServer(){
		
		FtpServerFactory serverFactory = new FtpServerFactory();
		
		ListenerFactory factory = new ListenerFactory();
	
		// set the port of the listener
		factory.setPort(21);
	
		PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
		userManagerFactory.setFile(new File("src/main/resources/users.properties"));
		userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
	
		UserManager userManager = userManagerFactory.createUserManager();
	
		serverFactory.setUserManager(userManager);
	
		// replace the default listener
		serverFactory.addListener("default", factory.createListener());
	
		// start the server
		FtpServer server = serverFactory.createServer();
	
		try
		{
			server.start();
		}
		catch (FtpException exception)
		{
			exception.printStackTrace();
		}
	}

    public static void main(String[] args) {

    	startServer();
    	
        FTPClient ftp = new FTPClient();

        try {
            ftp.connect("localhost"); // try to connect

            if (!ftp.login("ftpuser", "ftpuser")) // login to server
            {
                ftp.disconnect();
                return;
            }
            int reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.logout();
                ftp.disconnect();
                return;
            }

            ftp.changeWorkingDirectory("messages");

            OutputStream output = new FileOutputStream("data/out/file.xml");
            ftp.retrieveFile("tmp", output); // transfer the file
            output.close();

            ftp.logout();
            ftp.disconnect();

        } catch (Exception ex) {
            ex.printStackTrace();
            
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                    
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }

        }
    }

}
